package com.hm.health.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.goodix.adapter.PropertyAdapter;
import com.goodix.callback.AbsOnHBDTestClientListener;
import com.goodix.comsdk.HBDOption;
import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.netstack.INetStackCallback;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.comsdk.testsdk.IHBDTestClient;
import com.goodix.entity.PropertyData;
import com.goodix.iot.libbase.utils.ArrayUtil;
import com.goodix.utils.TimeUtil;
import com.goodix.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.Constans;
import com.hm.health.Utils.FileLogUtil;
import com.hm.health.entity.BleDevicesInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenshi on 2020/4/23.
 */

public class BLELogCatActivity extends BaseActivity {

    @BindView(R.id.btn_connect)
    Button mBtnConnect;
    @BindView(R.id.edit_uuid)
    EditText mEditUUID;
    @BindView(R.id.lv_log)
    ListView mLvLog;
    @BindView(R.id.btn_save)
    Button mBtnSave;

    public static final int MSG_REFRESH_LOG_DATA = 1;

    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat sSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");

    private IHBDTestClient mTestClient;
    private HBDOption mHBDOption;
    private String notifyUUID;
    private FileLogUtil mFileSaveUtil;
    private String mDefaultNotifyUUID;
    private PropertyAdapter mPropertyAdapter;
    private List<PropertyData> mPropertyDataList = new ArrayList<>();
    private List<PropertyData> mBuffer = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_log_save);
        ButterKnife.bind(this);
        initActionBar(getString(R.string.ble_logcat));
        initView();

        mTestClient = MyApplication.getHBDTestClient();
        mHBDOption = mTestClient.getHBDOption();
        notifyUUID = mHBDOption.getNotifyUUID();
        mDefaultNotifyUUID = notifyUUID;
        mEditUUID.setText(notifyUUID);
        mTestClient.registerHBDDataListener(mOnHBDDataListener);
        mTestClient.registerTestCallback(mAbsOnHBDTestClientListener, mAbsOnHBDTestClientListener);
    }

    private void initView() {
        mPropertyAdapter = new PropertyAdapter(mContext, mPropertyDataList, R.layout.item_ble_log);
        mLvLog.setAdapter(mPropertyAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTestClient.disconnect();
        mTestClient.unRegisterHBDDataListener(mOnHBDDataListener);
        mTestClient.unRegisterTestCallback(mAbsOnHBDTestClientListener, mAbsOnHBDTestClientListener);
        mTestClient.getHBDOption().setNotifyUUID(mDefaultNotifyUUID);
    }

    @OnClick(R.id.btn_connect)
    protected void onBtnConnectClicked(View v) {
        if (mBtnConnect.getTag() == null) {
            mBtnConnect.setTag(false);
        }

        if ((boolean)mBtnConnect.getTag()) {
            mBtnConnect.setText(getString(R.string.device_disconnected));
            mTestClient.disconnect();
            mBtnConnect.setTag(false);
        } else {
            Intent intent = new Intent(mContext, LeDeviceListActivity.class);
            intent.putExtra(LeDeviceListActivity.ARG_IS_SINGLE_SELECTED, true);
            startActivityForResult(intent, 1);
        }
    }

    @OnClick(R.id.btn_save)
    protected void onBtnSaveClicked(View v) {
        if (mBtnSave.getTag() == null) {
            mBtnSave.setTag(false);
        }

        if (!(boolean)mBtnSave.getTag()) {
            String path = Constans.SERVER_ROMA_RAW_DATA_FOLDER + "ble_log";
            String fileName = String.format("%s-%s.log", TimeUtil.formateTime(System.currentTimeMillis()),
                    MyApplication.getUserName());
            mFileSaveUtil = new FileLogUtil(path,fileName);
            mFileSaveUtil.startSave();
            mBtnSave.setText(R.string.stop_save);
            mBtnSave.setTag(true);
        } else {
            if (null != mFileSaveUtil) {
                mFileSaveUtil.finishedSave();
            }
            mBtnSave.setText(R.string.start_save);
            mBtnSave.setTag(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }

        String str = data.getStringExtra(LeDeviceListActivity.SELECTED_BLE_DEVICES);
        if (null == str || str.isEmpty()) {
            return;
        }

        ArrayList<BleDevicesInfo> devicesInfo = new Gson().fromJson(str,
                new TypeToken<ArrayList<BleDevicesInfo>>(){}.getType());
        if (null == devicesInfo || devicesInfo.isEmpty()) {
            return;
        }

        mHBDOption.setNotifyUUID(mEditUUID.getText().toString().trim());
        mBtnConnect.setText(getString(R.string.connecting));
        mBtnConnect.setEnabled(false);
        mTestClient.connect(devicesInfo.get(0));
    }

    AbsOnHBDTestClientListener mAbsOnHBDTestClientListener = new AbsOnHBDTestClientListener() {
        @Override
        public void onConnected(int errCode) {
            super.onConnected(errCode);
            mBtnConnect.setText(getString(R.string.connected));
            mBtnConnect.setEnabled(true);
            mBtnConnect.setTag(true);
            mBtnSave.setEnabled(true);
        }

        @Override
        public void onError(int errCode, String message) {
            super.onError(errCode, message);
            ToastUtils.showLongToastMessage(mContext, message);
        }

        @Override
        public void onDisconnected(int errCode) {
            mBtnConnect.setText(getString(R.string.device_disconnected));
            mBtnConnect.setEnabled(true);
            mBtnConnect.setTag(false);
            mBtnSave.setEnabled(false);

            if ((boolean)mBtnSave.getTag()) {
                onBtnSaveClicked(mBtnSave);
            }
        }
    };

    OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {
        @Override
        public void onDataChanged(String dataType, int[] dataArr) {
            if (dataType.equals(INetStackCallback.DATA_TYPE_PPG_RAW_DATA)) {
                if (null != mFileSaveUtil) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(sSimpleDateFormat.format(new Date())).append(",");
                    sb.append(ArrayUtil.intArrToHexString(dataArr)).append("\n");
                    mFileSaveUtil.saveData(sb.toString());
                }
            }


            synchronized (mBuffer) {
                mBuffer.add(new PropertyData(sSimpleDateFormat.format(new Date()),
                        ArrayUtil.intArrToHexString(dataArr)));
            }

            if (!mHandler.hasMessages(MSG_REFRESH_LOG_DATA)) {
                mHandler.sendEmptyMessageAtTime(MSG_REFRESH_LOG_DATA, 40);
            }
        }

        @Override
        public void onMeasureResult(MeasureResult result) {

        }
    };

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case MSG_REFRESH_LOG_DATA:
                    synchronized (mBuffer) {
                        mPropertyAdapter.notifyDataSetChanged();
                        int len = mPropertyDataList.size() + mBuffer.size() - 100;
                        while (len-- > 0) {
                            mPropertyDataList.remove(0);
                        }
                        mPropertyDataList.addAll(mBuffer);
                        mBuffer.clear();
                        mPropertyAdapter.notifyDataSetChanged();
                        mLvLog.setSelection(mPropertyDataList.size());
                    }
                    break;
            }
            return false;
        }
    });

}
